<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends MY_Controller {

	function __construct() {
		parent::__construct();
	}
	
	public function index()
	{
		if ($this->isSessionActive()) {
		
			$this->load->model("Home_model");
			
			$data['offers'] = $this->Home_model->get_offers($this->fb_id);
			$data['requests'] = $this->Home_model->get_requests($this->fb_id);
			$data['new_items'] = $this->Home_model->get_new_items($this->fb_id);
			
			$data['user'] = $this->fb_id;
			$data['title'] = 'Home';
			$data['content_view'] = 'home_view';
			$data['stylesheets'] = array('homepage', 'paginate-style');
			$data['javascripts'] = array('homepage', 'paginate', 'homepage_paginate', 'slider', 'tooltip');

    		$this->load_template_view($data, TRUE);
		}
	}
	
	// loads registration page
	function register() {
		$data['title'] = 'Register';
		$data['content_view'] = 'register_view';
		$data['stylesheets'] = array();
		$data['javascripts'] = array();
		$this->load_template_view($data, FALSE);
	}
	
	// processes information from registration form
	function register_user() {
		if ($_REQUEST && !$this->fb_cookie) {
			//To extract the user's details
			$response = $this->parse_signed_request($_REQUEST['signed_request'], $this->config->item('fb_secret'));
       		
			$this->load->model('User_model');
			$query = $this->User_model->create_user($response);
			
			// saves Facebook User ID
			$this->fb_id = $response['user_id'];
			
			if ($query) {
				$this->load->model('Notification_model');
				$message = "Hi there! Welcome to The Trove. Lost and unsure of what to do? Check out our <a href='". base_url('/help/') . "'Help / Getting Started</a> page!. You can always find the link to the help page at the bottom of our website. This website is in its beta version and is still currently under development. As a result, there may still be bugs hiding around. We hope that you will bear with us as we continue to fix and develop this website. In the meantime, do feel free to drop us bug reports or any other comments and feedback through the feedback form located on the left side of the website. Thanks, and we hope you enjoy using this website!";
				$this->Notification_model->create_notification($this->fb_id, $message);
				$message = 'Spread the word, and <a href="Javascript:void(0);" onclick="shareTheTrove(\''.base_url().'\');">share</a> this website on your facebook wall! The more people using this website, the more items will be put up on offer!';
				$this->Notification_model->create_notification($this->fb_id, $message);
				redirect('');
			}
			else {
				log_message('error', 'Unable to add user to database!');
				show_error('We are unable to process your registration. Please contact our technical support (cs3216-recycle@googlegroups.com)');
			}
		}
		else {
			log_message('error', 'Failed to parse signed_request from Facebook!');
			show_error('We are unable to process your registration. Please contact our technical support (cs3216-recycle@googlegroups.com)');
		}
	}
	
	//For use of facebook registration
	private function parse_signed_request($signed_request, $secret) {
		list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

		// decode the data
		$sig = $this->base64_url_decode($encoded_sig);
		$data = json_decode($this->base64_url_decode($payload), true);

		if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
			error_log('Unknown algorithm. Expected HMAC-SHA256');
			return null;
		}

		// check sig
		$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
		if ($sig !== $expected_sig) {
			error_log('Bad Signed JSON signature!');
			return null;
		}

		return $data;
	}
	
	//For use of facebook registration
	private function base64_url_decode($input) {
		return base64_decode(strtr($input, '-_', '+/'));
	}
	
	function remove_request()
	{
		$type = $_POST['status'];
		$id = $_POST['offer_id'];
		$this->load->model("Home_model");
		
		$details = $this->Home_model->get_offer_details($id);
		
		if ($type == 'offeredtoyou') //notify the owner of the item, and notify all 'offered to someone else' people
		{
			$this->Home_model->remove_from_database('request', $this->fb_id, $id);
			$this->load->model("Notification_model");
			
			$message = "<a href='".base_url('/itemdescription/')."/".$details[0]['offer_id']."'>".$details[0]['item_title']."</a> has been made available again. Your request has been noted.";
			$got_others = $this->Home_model->get_all_other('request', 'Offered to someone else', $id);
			if ($got_others)
			{
				$this->Home_model->change_status('request', $id, 'Offered to someone else', 'Pending', array('display'=>'1'));
				foreach($got_others as $person)
					$this->Notification_model->create_notification($person['fb_id'], $message);
			}
			
			$owner = $this->Home_model->get_owner($id);
			$this->Home_model->change_status('offer', $id, 'Reserved', 'Available');
			$message_for_owner = "<a href='".base_url('/profile/')."/".$this->fb_id."'><span class='get-fb-name'>".$this->fb_id."</span></a> has rejected your item: <a href='".base_url('/itemdescription/')."/".$details[0]['offer_id']."'>".$details[0]['item_title']."</a>. All other interested parties have been notified. You may wish to offer the item to someone else.";
			$this->Notification_model->create_notification($owner[0]['fb_id'], $message_for_owner);
			
		}
		else if ($type == 'pending')
		{
			$this->Home_model->remove_from_database('request', $this->fb_id, $id);
		}
		else if ($type == 'offeredtosomeoneelse')
		{
			$this->Home_model->remove_from_database('request', $this->fb_id, $id);
		}
	}
	
	function remove_offer()
	{
		$status = $_POST['status'];
		$id = $_POST['offer_id'];
		$this->load->model("Home_model");
		$this->load->model("Notification_model");
		
		$details = $this->Home_model->get_offer_details($id);
		
		if ($status == 'available')
		{
			$this->Home_model->remove_from_database('offer', $this->fb_id, $id);
			$message = "<a href='".base_url('/profile/')."/".$details[0]['fb_id']."'><span class='get-fb-name'>".$details[0]['fb_id']."</span></a> has removed the item: ".$details[0]['item_title']." from his/her offer list. Your request has been closed.";
			$got_others = $this->Home_model->get_all_other('request', 'Pending', $id);
			foreach($got_others as $person)
			{
				$this->Home_model->remove_from_database('request', $person['fb_id'], $id);
				$this->Notification_model->create_notification($person['fb_id'], $message);
			}
		}
		else if ($status == 'reserved')
		{
			$got_others = $this->Home_model->get_all_other('request', 'Offered to someone else', $id);//notify others
			if($got_others)
			{
				$this->Home_model->change_status('request', $id, 'Offered to someone else', 'Pending', array('display'=>'1'));
				$message = "<a href='".base_url('/itemdescription/')."/".$details[0]['offer_id']."'>".$details[0]['item_title']."</a> has been made available again. Your request has been noted.";
				foreach($got_others as $person)
				{
					$this->Notification_model->create_notification($person['fb_id'], $message);
				}
			}
			$this->Home_model->change_status('offer', $id, 'Reserved', 'Available');//change status
			$offered_person = $this->Home_model->get_all_other('request', 'Offered to you', $id);//notify reserved
			$this->Home_model->remove_from_database('request', $offered_person[0]['fb_id'], $id);
			$message = "<a href='".base_url('/profile/')."/".$details[0]['fb_id']."'><span class='get-fb-name'>".$details[0]['fb_id']."</span></a> has rejected your reservation for the item: <a href='".base_url('/itemdescription/')."/".$details[0]['offer_id']."'>".$details[0]['item_title']."</a>. If you still want the item, make a request for it again.";
			$this->Notification_model->create_notification($offered_person[0]['fb_id'], $message);
		}
	}
	
	function send_email()
	{
		$name = stripcslashes($_POST['name']);
		if (array_key_exists('email',$_POST) && $_POST['email'])
			$emailAddr = stripcslashes($_POST['email']);
		else
			$emailAddr = 'thetrove@thetrove.com';
		$comment = stripcslashes($_POST['message']);
		$subject = stripcslashes($_POST['subject']);
		
		
		$this->load->library('email');
		$this->email->from("thetrove.sg@gmail.com", $name);
		$this->email->to('thetrove.sg@gmail.com'); 

		$this->email->subject($subject);
		$this->email->message($emailAddr . ' - ' . $comment);	

		if ($this->email->send())
			echo('success');
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */